/*
* This file is a part of the open-eBackup project.
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* Copyright (c) [2024] Huawei Technologies Co.,Ltd.
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*/
#include "DistributedStorageMgr.h"


using namespace std;
using namespace VirtPlugin;

HCS_PLUGIN_NAMESPACE_BEGIN

int DistributedStorageMgr::CheckDistributedConnection(const ControlDeviceInfo &info, std::string &errorStr)
{
    GetFusionStorageRequest request;
    request.SetFusionStoragePort(info.m_port);
    request.SetFusionStorageUserName(info.m_userName);
    request.SetFusionStoragePassword(info.m_password);
    AuthObj storageAuth;
    storageAuth.name = info.m_userName;
    storageAuth.passwd = info.m_password;
    storageAuth.certVerifyEnable = info.m_enableCert;
    storageAuth.cert = info.m_cert;
    storageAuth.revocationList = info.m_revocationList;
    for (auto& ip : info.m_ipList) {
        request.SetEnvAddress(ip);
        if (DoCheckDistributedConnection(request, storageAuth) != SUCCESS) {
            errorStr = ip;
            ERRLOG("Failed to check distributed connection, errorip: %s.", errorStr.c_str());
            return FAILED;
        }
    }
    return SUCCESS;
}

int DistributedStorageMgr::DoCheckDistributedConnection(GetFusionStorageRequest& request,
    AuthObj& storageAuth)
{
    FusionStorageClient client;
    std::shared_ptr<ResponseModel> response = client.GetToken(request, storageAuth);
    if (response == nullptr ||
        (response->GetStatusCode() != static_cast<uint32_t>(HcsExternalStatusCode::OK))) {
        ERRLOG("Failed to get response, response is null.");
        return FAILED;
    }

    std:string body = response -> GetBody();
    std::string x_auth_token = "x_auth_token";
    size_t pos = body.find(x_auth_token);
    if (pos == std::string::npos) {
        ERRLOG("In the response does not contain token, please check the request parameters.");
        return FAILED;
    }
    return SUCCESS;
}

HCS_PLUGIN_NAMESPACE_END